package com.zdd.chap6.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdd.chap6.entity.Student;
import com.zdd.chap6.service.StudentService;
import com.zdd.chap6.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/students")
public class StudentController {
    @Autowired
    StudentService studentService;
    @GetMapping
    public ResultVo<?> findAllStudents(){
        List<Student> students=studentService.list();
        return ResultVo.success("展示所有学生成功!",students);
    }

    @GetMapping("/pageList")
    public ResultVo<?> findPage(@RequestParam(defaultValue = "",required = false)String stuName,@RequestParam(defaultValue = "1")Integer pageNum){
        LambdaQueryWrapper<Student> queryWrapper=new LambdaQueryWrapper<>();
        if(StringUtils.hasText(stuName)){
            queryWrapper.like(Student::getStudentname,stuName);
        }
        Page page=new Page();
        page.setCurrent(pageNum);
        page.setSize(5);
        Page<Student> pageList=studentService.page(page,queryWrapper);
        return ResultVo.success("查询学生成功!",pageList);
    }

    @PostMapping
    public ResultVo<?> save(@RequestBody Student student){
        studentService.save(student);
        return ResultVo.success("添加成功!",null);
    }

    @PutMapping
    public ResultVo<?> update(@RequestBody Student student){
        studentService.updateById(student);
        return ResultVo.success("修改成功！",null);
    }

    @DeleteMapping("/{id}")
    public ResultVo<?> delete(@PathVariable long id){
        studentService.removeById(id);
        return ResultVo.success("删除成功！",null);
    }
}
